package com.itqf.demo01;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/16
 * @Time: 下午2:32
 */
public class TestZKLock {

    public  static  void  main(String[]args){
        //1,重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,2);

        //2.CuratorFramework
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString("192.168.82.168:2181,192.168.82.168:2182,192.168.82.168:2183")
                .retryPolicy(retryPolicy)
                .connectionTimeoutMs(3000)
                .build();
        //3.启动
        cf.start();

        //4.  /lock
        //      /lock000000001
        //      /lock000000002
        InterProcessMutex lock = new InterProcessMutex(cf,"/lock");
        //lock.acquire();//获取分布式锁
        //_c_01c44d2b-6f1d-4ea2-bfe3-2a5718ff7296-lock-0000000091
        //lock.release();//释放锁
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    lock.acquire();
                    System.out.println(Thread.currentThread().getName()+"---获取锁");
                    System.out.println(Thread.currentThread().getName()+"执行业务(秒杀....)");
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    try {
                        System.out.println(Thread.currentThread().getName()+"执行业务完毕！！");
                        lock.release();//释放锁
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        };

        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }


        try {
            TimeUnit.SECONDS.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
